package com.lagou.lagourocketmq.service;


import com.alibaba.fastjson.JSON;
import com.lagou.lagourocketmq.config.RedisLock;
import com.lagou.lagourocketmq.mapper.SkuMapper;
import com.lagou.lagourocketmq.pojo.Order;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

@Service
@RocketMQMessageListener(topic = "lagou-orderDelay", consumerGroup = "orderDelay")
public class ConsumerDelayService implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisLock redisLock;


    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            String orderStr = new String(messageExt.getBody(), "utf-8");
            Order order = JSON.parseObject(orderStr, Order.class);
            RBucket<Object> orderbucket = redissonClient.getBucket("order:" + order.getOrderId());
            String orderRedisStr = (String)orderbucket.get();
            Order orderredis = JSON.parseObject(orderRedisStr, Order.class);
//            System.out.println(orderStr);
            //检查redis中订单的状态
            if(orderredis.getStatus().equals("paid")){
                //修改数据库中的商品数量
                skuMapper.updateAcount("123");//商品减一
                System.out.println("扣减库存，交易成功！");

            }else {
                //如果没有支付，把redis中的数量加回去
                Boolean skuLock = redisLock.lock("skuLock");
                if(skuLock){
                    RBucket<Object> bucket = redissonClient.getBucket("sku:123");
                    bucket.set((Integer)bucket.get()+1);

                    redisLock.unlock("skuLock");
                    System.out.println("订单超时支付："+new String(messageExt.getBody(),"utf-8"));
                }

            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }finally {

        }

    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {

    }
}
